import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import Layout from '@/layout/index.vue'
import { useMenuStore } from '@/stores/menu'
import FormTest from '@/views/formtest.vue' // 引入新的表单页面组件
// 常量定义
const LOGIN_PATH = '/login'
const HOME_PATH = '/'

// 路由配置
const routes : RouteRecordRaw[] = [
	{
		path: LOGIN_PATH,
		name: 'Login',
		component: () => import('@/views/login/index.vue'),
		meta: {
			title: '登录',
			requiresAuth: false
		}
	},
	{
		path: HOME_PATH,
		component: Layout,
		children: [],  // 子路由将由后端返回的菜单动态生成
		meta: {
			requiresAuth: true
		}
	},
	{
	    path: '/form', // 新增的表单页面路由
	    name: 'FormTest',
	    component: FormTest,
	    meta: {
	      requiresAuth: false // 不需要登录校验
	    }
	  }
]

// 创建路由实例
const router = createRouter({
	history: createWebHistory(),
	routes
})

// 获取token工具函数
const getToken = () : string | null => localStorage.getItem('token')

// 重定向到登录页
const redirectToLogin = (to : RouteLocationNormalized) : { path : string, query : any } => {
	return {
		path: LOGIN_PATH,
		query: { redirect: to.fullPath }
	}
}

// 路由守卫
router.beforeEach(async (
	to : RouteLocationNormalized,
	from : RouteLocationNormalized,
	next : NavigationGuardNext
) => {
	const token = getToken()
	const menuStore = useMenuStore()

	try {
		// 处理已登录状态
		if (token) {
			if (to.path === LOGIN_PATH) {
				return next(HOME_PATH)
			}

			if (!menuStore.routesAddedData()) {
				await menuStore.getMenus()
				return next({ ...to, replace: true })
			}

			return next()
		}

		// 处理未登录状态
		if (to.meta.requiresAuth) {
			return next(redirectToLogin(to))
		}
		// 如果访问的是/form路径，允许未登录用户访问
		if (to.path === '/form') {
			return next()
		}
		return next()
	} catch (error) {
		console.error('路由守卫发生错误:', error)
		return next(redirectToLogin(to))
	}
})

export default router